package com.mpq.controler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

/**
 * @author mingpingqiang on 2018/12/4/11:34
 * Created by mingpingqiang on 2018/12/4/11:34
 */
@RestController
@RequestMapping("/mpq/mail")
public class MailController {
    private static final Logger log = LoggerFactory.getLogger(MailController.class);
    @Autowired
    private JavaMailSender javaMailSender;

    /**
     * 发送简单邮件
     * @return
     */
    @RequestMapping("/sendMailSample")
    public String sendMailSample() {
        SimpleMailMessage message = new SimpleMailMessage();
        //发件人
        message.setFrom("594985930@qq.com");
        //收件人
        message.setTo("1145801282@qq.com");
        message.setSubject("邮件标题");
        message.setText("邮件内容");
        javaMailSender.send(message);
        return "发送成功";
    }

    /**
     * 发送含附件的邮件
     * @return
     * @throws MessagingException
     */
    @RequestMapping("/sendMailAttachment")
    public String sendMailAttachment() throws MessagingException {
        //需要创建一个MimeMessageHelper对象，相关参数和简单邮件类似
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
        helper.setFrom("594985930@qq.com");
        helper.setTo("1145801282@qq.com");
        helper.setSubject("邮件标题");
        //将邮件内容设置为html格式
        helper.setText("<html><body><h1>hello world</h1></body></html>",true);
        //定义文件，这是java.main.resources也就是classpach路径下的文件abc.png
        ClassPathResource file = new ClassPathResource("/static/meinv.jpg");
        //添加附件文件， 设置文件名为abc.png
        helper.addAttachment("美女.jpg", file);
        javaMailSender.send(mimeMessage);
        return "发送成功";
    }
}
